
package com.trp.app;

import com.trp.service.ILoaderService;
import com.trp.service.LoaderService;
import com.trp.view.LoadException;
import com.trp.view.ViewLoader;
import com.trp.view.Workspace;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.view.KeyEvent;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MainActivity extends Activity {

    private static final int INIT = 0x001;

    private static final int LOAD_DONE = 0x002;

    private static final int MAIN_LOAD_CONFIG_PROCESS_DIALOG = 0x0001;

    private static final int MAIN_LOAD_DATA_PROCESS_DIALOG = 0x0002;

    private static final int MAIN_CLOSE_PROCESS_DIALOG = 0x0003;

    private static final int MAIN_LOAD_ERROR = 0x1000;

    private static final int MAIN_LOAD_CONFIG_ERROR = 0x1001;

    private ViewLoader vl;

    private Handler handler;

    private Handler mainHandler;

    private Context context;

    private ILoaderService loader;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        setContentView(R.layout.main);
        LinearLayout ll = (LinearLayout)this.findViewById(R.id.ts);
        ViewGroup workspace = new Workspace(this);
        ll.addView(workspace, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
                LinearLayout.LayoutParams.FILL_PARENT));

        vl = (ViewLoader)workspace;

        // TODO should use remote service instead
        loader = new LoaderService();

        final Object lock = new Object();
        HandlerThread thread = new HandlerThread("handler") {

            @Override
            public void run() {
                Looper.prepare();
                handler = new CmdHandler(Looper.myLooper());
                synchronized (lock) {
                    lock.notifyAll();
                }
                Looper.loop();
            }
        };
        thread.start();

        // TODO should use another way instead it. because in some case, may be
        // it waits for a long time,
        synchronized (lock) {
            try {
                lock.wait(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        mainHandler = new MainHandler();

        Message m = handler.obtainMessage(INIT);
        handler.sendMessage(m);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        vl.unLoad();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        String message = this.getString(R.string.quit_message);
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage(message == null ? "Do you want to quit?" : message)
                    .setCancelable(false)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            MainActivity.this.finish();
                        }
                    }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });

            AlertDialog alert = builder.create();
            alert.show();
            return true;
        }

        return false;

    }

    class CmdHandler extends Handler {

        public CmdHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            switch (what) {
                case INIT:
                    mainHandler.obtainMessage(MAIN_LOAD_CONFIG_PROCESS_DIALOG).sendToTarget();
                    try {
                        vl.loadConfig(loader);
                    } catch (LoadException e) {
                        e.printStackTrace();
                        mainHandler.obtainMessage(MAIN_LOAD_CONFIG_ERROR).sendToTarget();
                        break;
                    }
                    mainHandler.obtainMessage(MAIN_LOAD_DATA_PROCESS_DIALOG).sendToTarget();
                    try {
                        vl.load(loader);
                    } catch (LoadException e) {
                        e.printStackTrace();
                        mainHandler.obtainMessage(MAIN_LOAD_ERROR).sendToTarget();
                        break;
                    }

                    mainHandler.obtainMessage(MAIN_CLOSE_PROCESS_DIALOG).sendToTarget();
                    break;
            }
        }
    }

    class MainHandler extends Handler {
        ProgressDialog pd;

        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            switch (what) {
                case MAIN_LOAD_CONFIG_PROCESS_DIALOG:
                    pd = ProgressDialog.show(context, "",
                            context.getResources().getString(R.string.load_config_waiting), true,
                            false);
                    break;
                case MAIN_LOAD_DATA_PROCESS_DIALOG:
                    pd.setMessage(context.getResources().getString(R.string.load_waiting));
                    break;
                case MAIN_CLOSE_PROCESS_DIALOG:
                    pd.dismiss();
                    pd = null;
                    break;
                case MAIN_LOAD_ERROR:
                case MAIN_LOAD_CONFIG_ERROR:
                    if (pd != null) {
                        pd.dismiss();
                        pd = null;
                    }
                    System.out.println("=================");
                    Toast toast = Toast.makeText(context, R.string.load_error, Toast.LENGTH_LONG);
                    toast.show();
                    break;
            }
        }
    }
}
